import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { _HttpClient, ModalHelper,SettingsService } from '@delon/theme';
import {SimpleTableButton, SimpleTableColumn, SimpleTableComponent} from '@delon/abc';
import { NzMessageService, NzModalService, NzTabChangeEvent, UploadFile, NzNotificationService } from 'ng-zorro-antd';
import { CommService } from 'app/service/comm/comm.service';
import { Constant, ServiceResult } from '@core/constant';
import { EmitterService } from 'app/service/emit.service';
import {ActivatedRoute, Router} from '@angular/router';
import { plService } from '../../../service/pl/pl.service';
import {fkService} from "../../../service/fk/fk.service";
import { ProductService } from '../../../service/prod/product.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { Timeout } from '@shared/descriptor/timeout';
import {formatDate} from "@angular/common";


@Component({
  selector: 'replan-list',
  templateUrl: './replan-list.component.html',
  styleUrls: ['./replan-list.component.less']
})
export class plListComponent implements OnInit, OnDestroy {
  // region 公共字段
  product:  any = {
    id:null,
    orderNo: null,
    bpmStatus:null,
    orderInfo: null,
    cusName: null,
    refPeriod: null,
    refTotalPeriod: null /*No show*/,
    refDate: null,
    refFbenjin: null,
    refAmount: null,
    refLixi: null,
    refSybenjin: null,
    reMark: null,
    payAmount: null,
    fxjOut58: null, /* 逾期天数 */
    fxjOut59:null /* 实际还款日期 */
  };

  productjq:  any = {
    id:null,
    bmDate: null,
    bmTime: null,
    bxRq: null,
    carColor: null,
    carDetail: null,
    carVin: null,
    conJson: null,
    conNo: null,
    conType: null,
    conUrl: null,
    createSysorg: null,
    createUser: null,
    cusAge: null,
    cusBirthday: null,
    cusDeu: null,
    cusEthnical: null,
    cusGender: null,
    cusIdValidfrom: null,
    cusIdValidto: null,
    cusIncard: null,
    cusMaritalStatus: null,
    cusMobile: null,
    cusName: null,
    cusQqid: null,
    cusRemark: null,
    cusResAddr: null,
    cusWechatid: null,
    cusrIdtype: null,
    danganNo: null,
    diyaStatus: null,
    diyaUser: null,
    fangkBank: null,
    fangkId: null,
    fangkName: null,
    fangkType: null,
    fkAmount: null,
    gpsInsAddr: null,
    gpsInsData: null,
    gpsInsMobile: null,
    gpsInsUser: null,
    gpsStatus: null,
    gpsUser: null,
    guohuStatus: null,
    guohuUser: null,
    luqiaoRq: null,
    lxMobile1: null,
    lxMobile2: null,
    lxMobile3: null,
    lxName1: null,
    lxName2: null,
    lxName3: null,
    mpName: null,
    mpUrl: null,
    mpbackUrl: null,
    nianjiaRq: null,
    orderAmount: null,
    orderArea: null,
    orderBy1: null,
    orderBy10: null,
    orderBy11: null,
    orderBy12: null,
    orderBy13: null,
    orderBy14: null,
    orderBy15: null,
    orderBy16: null,
    orderBy17: null,
    orderBy18: null,
    orderBy2: null,
    orderBy3: null,
    orderBy4: null,
    orderBy5: null,
    orderBy6: null,
    orderBy7: null,
    orderBy8: null,
    orderBy9: null,
    orderBy27:null,

    orderBy28:null,

    orderBy29:null,

    orderBy30:null,
    orderCarno: null,
    orderCartype: null,
    orderInfo: null,
    orderNo: null,
    orderOper: null,
    orderPeriod: null,
    orderStatus: null,
    proClass: null,
    proIsdb: null,
    proName: null,
    proNo: null,
    proType: null,
    proWf: null,
    qiandanUser: null,
    sfAnpaijiafang: null,
    sfDianshen: null,
    wbName: null,
    wbUrl: null,
    wbbackUrl: null,
    yinhangUser: null,
    dypname: null,
    dypvalue: null,
    dypyear: null,
    dyptype: null,
    dypclass: null,

    dypremark1: null,
    dypremark2: null,
    dypremark3: null,
    emergencyRelation:  null,
    emergencyContact: null,
    emergencyMobile: null,
    emergencyOffice:null,
    emergencyResAddr:null,
    spcomment:'同意',
    bt1:null,
    bt2:null,
    bt3:null,
  };

  productzd: any = {
    id:null
  }

  visible = false;
  // pageSize
  ps = 10;
  // 搜索表单
  q: any = {
    bpmStatus:"",
    pxtype:'asc',
    cusName: '',
    cusMobile: '',
    orderInfo: '',
    orderNo: '',
    dateRange: null,
    startDate:'',
    endDate:''
  };

  allDelBtnShow = false;
  isFetching = false;

  loading = false;
  // 表格组件
  @ViewChild('st') st: SimpleTableComponent;
  // 表格数据url
  url = this.plService.list();
  // region end

  // 搜索区域显示/隐藏标记
  // 显示图片
  previewVisible = false;
  // 大图地址
  previewImage = '';
  imgSuffix = '';

  years = [];
  userGroups = [];
  brands = [];
  isAds = [{ text: '广告款', value: this.cnt.BoolUtil.TRUE}, { text: '普通款', value: this.cnt.BoolUtil.FALSE }];
  isCms = [{ text: '是', value: this.cnt.BoolUtil.TRUE}, { text: '否', value: this.cnt.BoolUtil.FALSE }];
  seasons = [];
  checkedList = [];
  data = [];
  bpmStatus =  [{text: '未还款', value: '1'}, {text: '已还款', value: '10'}, {text: '已结清', value: '90'}, {text: '已拖车', value: '91'}];

  uploadUrl = this.plService.uploadProds();
  uploadDateUrl = this.plService.batchRepdate();


  columns: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '状态', index: 'bpmStatus', render: 'bpmStatus' },
    { title: '订单编号 ', index: 'orderNo' },
    { title: '客户姓名' , index: 'cusName' },
    { title: '期数', index: 'refPeriod' },
    { title: '总期数', index: 'refTotalPeriod' },
    { title: '应还款日期', index: 'refDate' },
    { title: '需还款总金额', index: 'refAmount' },
    { title: '利息', index: 'refLixi' },
    { title: '逾期天数', index: 'fxjOut58' },
    { title: '备注', index: 'reMark' },
    {
        title: '操作',
        buttons: [
            {
              text: '还款',
              type: 'link',
              click: (record: any) => {
                return this.getProductInfo(record.id);
              },
              iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
                return item.bpmStatus === '未还款'
              }
            },
            {
              text: '催收',
              type: 'link',
              click: (record: any) => this.router.navigate(['/notice/notice/query/'+record.orderNo]),
              iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
                return item.bpmStatus === '未还款'
              }
            }
        ]
    }
  ];


  columnsjq: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '订单编号', index: 'orderNo' },
    { title: '订单状态', index: 'orderStatus' },
    { title: '客户姓名 ', index: 'cusName'},
    { title: '身份证号 ', index: 'cusIncard' },
    { title: '联系电话', index: 'cusMobile' },
    { title: '申请金额 ', index: 'orderAmount' },
    { title: '申请期数 ', index: 'orderPeriod' },
    { title: '车辆信息 ', index: 'cusRemark' },
    { title: '录入业务员  ' , index: 'createBy' },
    { title: '订单提交时间', index: 'createDate' },
    { title: '审批人员', index: 'updateBy' },
    {
        title: '操作',
        buttons: [
          {
            text: "结清",
            type: 'link',
            click: (record: any) => this.router.navigate(['/prod/product/jq/'+record.id])
          },          {
            text: "订单详情",
            type: 'link',

            click: (record: any) => this.router.navigate([record.wbUrl+record.id])
          }
        ]
    }
  ]



  constructor(
    public setting: SettingsService,
    private trans: TranslateService,
    public http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: ModalHelper,
    private comm: CommService,
    private cnt: Constant,
    private plService: plService,
    private fkService: fkService,
    private productService: ProductService,
    private emit: EmitterService,
    private router: Router,
    private modalService: NzModalService,
    private notice: NzNotificationService,
    private route: ActivatedRoute,

  ) {}
  syncing = false;
  lastDate = null;
  private sub: any;

  ngOnDestroy() {
    if (this.inter) {
      clearInterval(this.inter);
    }
  }


  inter
  ngOnInit() {

    this.imgSuffix = this.comm.getGoodsUrl();
    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      let varinpur = params["id"];
      if(varinpur){
        this.q.orderNo = params["id"];
      }
    });
    this.emit.getMessage().subscribe(data => {
      if (data.text === 'RELOAD_GOODS_LIST') {
        this.st.load(1, this.q);
      }
    })

  }

  fullChange(val: boolean) {
    // this.scroll = val ? { y: '350px' } : { y: '230px' };
  }

  back() {
    this.router.navigate(['/prod/product/80']);
  }

  change(args: NzTabChangeEvent) {
        switch (args.index) {
          case 0:
            this.q.bpmStatus = "";
            this.columns = this.columns;
            this.url = this.plService.list();
            this.allDelBtnShow = false;
            break;
          case 1:
            this.q.bpmStatus = "未还款";
            this.columns = this.columns;
            this.url = this.plService.list();
            this.allDelBtnShow = false;
            break;
          case 2:
            this.q.bpmStatus = "已还款";
            this.columns = this.columns;
            this.url = this.plService.list();
            this.allDelBtnShow = false;
            break;
          case 3:
            // this.q.bpmStatus = "已结清";
            this.columns = this.columnsjq;
            this.url = this.productService.list();
            this.allDelBtnShow = true;
            break;
          case 4:
            this.q.bpmStatus = "已拖车";
            this.columns = this.columns;
            this.url = this.plService.list();
            this.allDelBtnShow = false;
            break;

          default:
            break;
        }
      this.st.load(1, this.q);
  }

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  // 删除
  alldelete(){
    console.log(this.checkedList);
    for(let i=0;i<this.checkedList.length;i++){
      console.log(this.checkedList[i].id);
      this.plService.delProduct(this.checkedList[i].id).pipe(
        catchError(err => {
          return of(err);
        })
      ).subscribe(data => {
        console.log("log"+JSON.stringify(data));
        this.msg.success('删除成功');
        this.st.load(1, this.q);
        // this.product = data.data;
        // this.b(this.product.orderNo);
        // this.a();
      });
    }
  }

  gotoAdd() {
    setTimeout(() => {
      this.router.navigate(['/prod/product/add']);
    }, 500);
  }

  @Timeout(500)
  gotoImg() {
    this.router.navigate(['/prod/product/upload']);
  }


  selectProd: {[propName: string]: any;} = {}
  selectUrl = null;
  //还款
  getProductInfo(id){
    console.log('a');
    console.log(id);
    this.plService.getProduct(id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      console.log("log"+JSON.stringify(data));
      this.product = data.data;
      this.b(this.product.orderNo);
    });
    
  }

  //通过还款订单号查询主表的id
//BHRZ20180911001
  b(orderNo){
    console.log(orderNo);
    this.plService.getProducta(orderNo).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if(data.ok){
        console.log("log"+JSON.stringify(data));
        this.productzd.id = data.data.id;
        console.log(this.productzd.id);
      }
    });
  }

  view(record) {
    this.plService.getProduct(record.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.selectProd = data.data;
      // 拼接图片地址
      this.selectUrl = this.comm.getGoodsUrl() + this.selectProd.img;
      this.visible = true;
    })

  }

  close(): void {
    this.visible = false;
  }



  cancel() {
    this.repdate = null;
  }
  repdate = null;



  uploadProd(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
        this.loading = true;
    }
    if (info.file.status === 'done') {
        this.loading = false;
        this.notice.create('success', 'Success', info.file.response.data['successTip']);
        if (undefined !== info.file.response.data['failTip']) {
          this.notice.create('info', 'Info', info.file.response.data['failTip']);
        }
        this.st.load();
    }
    if (info.file.status === 'error') {
        this.loading = false;
      this.notice.create('error', 'Error', info.file.response.msg);
    }
  }


  dateChange(result: Date[]): void {
    if (result.length !== 0) {
      this.q.startDate = formatDate(result[0], 'yyyy-MM-dd', 'en-US');
      this.q.endDate = formatDate(result[1], 'yyyy-MM-dd', 'en-US');
    } else {
      this.q.startDate = '';
      this.q.endDate = '';
    }
  }

  save() {
    let fxjPlReplan = {
      updateBy:this.setting.user.username,
      id:this.product.id,
      bpmStatus:this.product.bpmStatus,
      orderInfo: this.product.orderInfo,
      cusName: this.product.cusName,
      refPeriod: this.product.refPeriod,
      refTotalPeriod: this.product.refTotalPeriod /*No show*/,
      refDate: this.product.refDate,
      refFbenjin: this.product.refFbenjin,
      refAmount: this.product.refAmount,
      refLixi: this.product.refLixi,
      refSybenjin: this.product.refSybenjin,
      reMark: this.product.reMark,
      payAmount: this.product.payAmount,
      fxjOut58: this.product.fxjOut58,
      fxjOut59: this.product.fxjOut59,
    };
    let fxjPlReplana = {
      updateBy:null,
      id:null,
      bpmStatus:null,
      orderInfo: null,
      cusName: null,
      refPeriod: null,
      refTotalPeriod: null /*No show*/,
      refDate: null,
      refFbenjin: null,
      refAmount: null,
      refLixi: null,
      refSybenjin: null,
      reMark: null,
      payAmount: null,
      fxjOut58: null,
      fxjOut59: null,
    };
    
    
    // return false;
    if(this.product.bpmStatus!="90"){
      this.savehk(fxjPlReplan,fxjPlReplana);//还款操作
    }else{
      this.savejq();//结清操作
    }
    
  }

  // 还款保存
  savehk(fxjPlReplan,fxjPlReplana){
    console.log(fxjPlReplan);
    // 调用接口
    this.plService.editPro(fxjPlReplan).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      console.log(data);
      if (data.ok === true) {
        this.msg.success('修改成功');
        this.st.load(1, this.q);
        // this.product = fxjPlReplana;
        // this.emit.sendMessage("RELOAD_GOODS_LIST");
      } else {
        this.msg.error(data['message']);
      }
    });
  }

  // 结清订单
  savejq(){
    let fxjOrderLogList = [];
    // if(this.product.spcomment!=''){
      // console.log("this.product.dypname*********"+this.product.dypname);

      let dto ={
        orderNo:this.product.orderNo,
        logUser:this.setting.user.username,
        logContent:'结清'
      }
      fxjOrderLogList.push(dto);
    // }
    
    let fxjOrderMainPage = {
      updateBy:this.setting.user.username,
      id:this.productzd.id,
      orderNo:this.product.orderNo,
      orderOper:'S',


      bmDate: this.productjq.bmDate,
      bmTime: this.productjq.bmTime,
      bxRq: this.productjq.bxRq,
      carColor: this.productjq.carColor,
      carDetail: this.productjq.carDetail,
      carVin: this.productjq.carVin,
      conJson: this.productjq.conJson,
      conNo: this.productjq.conNo,
      conType: this.productjq.conType,
      conUrl: this.productjq.conUrl,
      createSysorg: this.productjq.createSysorg,
      createUser: this.productjq.createUser,
      cusAge: this.productjq.cusAge,
      cusBirthday: this.productjq.cusBirthday,
      cusDeu: this.productjq.cusDeu,
      cusEthnical: this.productjq.cusEthnical,
      cusGender: this.productjq.cusGender,
      cusIdValidfrom: this.productjq.cusIdValidfrom,
      cusIdValidto: this.productjq.cusIdValidto,
      cusIncard: this.productjq.cusIncard,
      cusMaritalStatus: this.productjq.cusMaritalStatus,
      cusMobile: this.productjq.cusMobile,
      cusName: this.productjq.cusName,
      cusQqid: this.productjq.cusQqid,
      cusRemark: this.productjq.cusRemark,
      cusResAddr: this.productjq.cusResAddr,
      cusWechatid: this.productjq.cusWechatid,
      cusrIdtype: this.productjq.cusrIdtype,
      danganNo: this.productjq.danganNo,
      diyaStatus: this.productjq.diyaStatus,
      diyaUser: this.productjq.diyaUser,
      fangkBank: this.productjq.fangkBank,
      fangkId: this.productjq.fangkId,
      fangkName: this.productjq.fangkName,
      fangkType: this.productjq.fangkType,
      fkAmount: this.productjq.fkAmount,
      gpsInsAddr: this.productjq.gpsInsAddr,
      gpsInsData: this.productjq.gpsInsData,
      gpsInsMobile: this.productjq.gpsInsMobile,
      gpsInsUser: this.productjq.gpsInsUser,
      gpsStatus: this.productjq.gpsStatus,
      gpsUser: this.productjq.gpsUser,
      guohuStatus: this.productjq.guohuStatus,
      guohuUser: this.productjq.guohuUser,
      luqiaoRq: this.productjq.luqiaoRq,
      lxMobile1: this.productjq.lxMobile1,
      lxMobile2: this.productjq.lxMobile2,
      lxMobile3: this.productjq.lxMobile3,
      lxName1: this.productjq.lxName1,
      lxName2: this.productjq.lxName2,
      lxName3: this.productjq.lxName3,
      mpName: this.productjq.mpName,
      mpUrl: this.productjq.mpUrl,
      mpbackUrl: this.productjq.mpbackUrl,
      nianjiaRq: this.productjq.nianjiaRq,
      orderAmount: this.productjq.orderAmount,
      orderArea: this.productjq.orderArea,
      orderBy1: this.productjq.orderBy1,
      orderBy10: this.productjq.orderBy10,
      orderBy11: this.productjq.orderBy11,
      orderBy12: this.productjq.orderBy12,
      orderBy27: this.productjq.orderBy27,
      orderBy28: this.productjq.orderBy28,
      orderBy29: this.productjq.orderBy29,
      orderBy13: this.productjq.orderBy13,
      orderBy14: this.productjq.orderBy14,
      orderBy15: this.productjq.orderBy15,
      orderBy16: this.productjq.orderBy16,
      orderBy17: this.productjq.orderBy17,
      orderBy18: this.productjq.orderBy18,
      orderBy2: this.productjq.orderBy2,
      orderBy3: this.productjq.orderBy3,
      orderBy4: this.productjq.orderBy4,
      orderBy5: this.productjq.orderBy5,
      orderBy6: this.productjq.orderBy6,
      orderBy7: this.productjq.orderBy7,
      orderBy8: this.productjq.orderBy8,
      orderBy9: this.productjq.orderBy9,
      orderCarno: this.productjq.orderCarno,
      orderCartype: this.productjq.orderCartype,
      orderInfo: this.productjq.orderInfo,

      orderPeriod: this.productjq.orderPeriod,
      orderStatus: this.productjq.orderStatus,
      proClass: this.productjq.proClass,
      proIsdb: this.productjq.proIsdb,
      proName: this.productjq.proName,
      proNo: this.productjq.proNo,
      proType: this.productjq.proType,
      proWf: this.productjq.proWf,
      qiandanUser: this.productjq.qiandanUser,
      sfAnpaijiafang: this.productjq.sfAnpaijiafang,
      sfDianshen: this.productjq.sfDianshen,
      wbName: this.productjq.wbName,
      wbUrl: this.productjq.wbUrl,
      wbbackUrl: this.productjq.wbbackUrl,
      yinhangUser: this.productjq.yinhangUser,
      fxjOrderLogList:JSON.parse(JSON.stringify(fxjOrderLogList))

    };
    console.log(JSON.stringify(fxjOrderMainPage));
    this.plService.editProsavejq(fxjOrderMainPage).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      console.log("data.ok"+data.ok);
      if (data.ok === true) {
        // this.savefk();
        this.msg.success('结清成功');
        this.st.load(1, this.q);
        this.emit.sendMessage("RELOAD_GOODS_LIST");
      } else {
        this.msg.error(data.respMsg);
      }
    });
  }

}
